package com.shark.security.jwt.security;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.shark.security.jwt.persistent.dao.PermissionRepository;
import com.shark.security.jwt.persistent.dao.UserRepository;
import com.shark.security.jwt.persistent.entity.PermissionInfoEntity;
import com.shark.security.jwt.persistent.entity.UserEntity;
import com.shark.security.jwt.security.model.JwtUserFactory;

/**
 * 取得用户信息
 * @author junxiao
 *
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	private UserRepository userDao;
    
//    @Autowired
//    private UserRoleRepository userRoleDao;
//
//    @Autowired
//    private RolePermissionRepository rolePermissionDao;

    @Autowired
    private PermissionRepository permissionDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserEntity user = userDao.getUserByLoginName(s);
        if (user == null) {
            return null;
        }
//        List<UserRoleEntity> listUserRole = userRoleDao.getByUserId(user.getId());
//        List<Integer> lisRole = new ArrayList<>();
//        for (UserRoleEntity e : listUserRole) {
//            lisRole.add(e.getRoleId());
//        }
//
//        List<RolePermissionEntity> lisRolePermission = rolePermissionDao.getPermissonByRole(lisRole);
//        List<Integer> lisPermissionId = new ArrayList<>();
//        for (RolePermissionEntity e : lisRolePermission) {
//            lisPermissionId.add(e.getPermissionId());
//        }
//        List<PermissionInfoEntity> lisPermission = permissionDao.getPermissonByRole(lisPermissionId);
        List<PermissionInfoEntity> lisPermission = permissionDao.getPermissonByLoginName(s);
        return JwtUserFactory.createJwtUser(user, lisPermission);
    }
}
